/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package service;

import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.DELETE;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.QueryParam;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.WebApplicationException;
import javax.persistence.NoResultException;
import javax.persistence.EntityManager;
import jpa.entities.Usuario;
import jpa.entities.UsuarioAdm;
import jpa.entities.Pedido;
import jpa.entities.UsuarioCli;
import java.util.Collection;
import converter.UsuarioConverter;
import javax.ejb.Stateless;

/**
 *
 * @author carlos
 */

@Stateless
public class UsuarioResource {
    @javax.ejb.EJB
    private UsuarioAdmCollectionResourceSub usuarioAdmCollectionResourceSub;
    @javax.ejb.EJB
    private PedidoCollectionResourceSub pedidoCollectionResourceSub;
    @javax.ejb.EJB
    private UsuarioCliCollectionResourceSub usuarioCliCollectionResourceSub;
    @Context
    protected UriInfo uriInfo;
    protected EntityManager em;
    protected Integer id;
  
    /** Creates a new instance of UsuarioResource */
    public UsuarioResource() {
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public void setEm(EntityManager em) {
        this.em = em;
    }

    /**
     * Get method for retrieving an instance of Usuario identified by id in XML format.
     *
     * @param id identifier for the entity
     * @return an instance of UsuarioConverter
     */
    @GET
    @Produces({"application/xml", "application/json"})
    public UsuarioConverter get(@QueryParam("expandLevel")
                                @DefaultValue("1")
    int expandLevel) {
        return new UsuarioConverter(getEntity(), uriInfo.getAbsolutePath(), expandLevel);
    }

    /**
     * Put method for updating an instance of Usuario identified by id using XML as the input format.
     *
     * @param id identifier for the entity
     * @param data an UsuarioConverter entity that is deserialized from a XML stream
     */
    @PUT
    @Consumes({"application/xml", "application/json"})
    public void put(UsuarioConverter data) {
        updateEntity(getEntity(), data.resolveEntity(em));
    }

    /**
     * Delete method for deleting an instance of Usuario identified by id.
     *
     * @param id identifier for the entity
     */
    @DELETE
    public void delete() {
        deleteEntity(getEntity());
    }

    /**
     * Returns an instance of Usuario identified by id.
     *
     * @param id identifier for the entity
     * @return an instance of Usuario
     */
    protected Usuario getEntity() {
        try {
            return (Usuario) em.createQuery("SELECT e FROM Usuario e where e.idUsuario = :idUsuario").setParameter("idUsuario", id).getSingleResult();
        } catch (NoResultException ex) {
            throw new WebApplicationException(new Throwable("Resource for " + uriInfo.getAbsolutePath() + " does not exist."), 404);
        }
    }

    /**
     * Updates entity using data from newEntity.
     *
     * @param entity the entity to update
     * @param newEntity the entity containing the new data
     * @return the updated entity
     */
    private Usuario updateEntity(Usuario entity, Usuario newEntity) {
        Collection<UsuarioCli> usuarioCliCollection = entity.getUsuarioCliCollection();
        Collection<UsuarioCli> usuarioCliCollectionNew = newEntity.getUsuarioCliCollection();
        Collection<Pedido> pedidoCollection = entity.getPedidoCollection();
        Collection<Pedido> pedidoCollectionNew = newEntity.getPedidoCollection();
        Collection<UsuarioAdm> usuarioAdmCollection = entity.getUsuarioAdmCollection();
        Collection<UsuarioAdm> usuarioAdmCollectionNew = newEntity.getUsuarioAdmCollection();
        entity = em.merge(newEntity);
        for (UsuarioCli value : usuarioCliCollection) {
            if (!usuarioCliCollectionNew.contains(value)) {
                throw new WebApplicationException(new Throwable("Cannot remove items from usuarioCliCollection"));
            }
        }
        for (UsuarioCli value : usuarioCliCollectionNew) {
            if (!usuarioCliCollection.contains(value)) {
                Usuario oldEntity = value.getUsuario();
                value.setUsuario(entity);
                if (oldEntity != null && !oldEntity.equals(entity)) {
                    oldEntity.getUsuarioCliCollection().remove(value);
                }
            }
        }
        for (Pedido value : pedidoCollection) {
            if (!pedidoCollectionNew.contains(value)) {
                throw new WebApplicationException(new Throwable("Cannot remove items from pedidoCollection"));
            }
        }
        for (Pedido value : pedidoCollectionNew) {
            if (!pedidoCollection.contains(value)) {
                Usuario oldEntity = value.getUsuario();
                value.setUsuario(entity);
                if (oldEntity != null && !oldEntity.equals(entity)) {
                    oldEntity.getPedidoCollection().remove(value);
                }
            }
        }
        for (UsuarioAdm value : usuarioAdmCollection) {
            if (!usuarioAdmCollectionNew.contains(value)) {
                throw new WebApplicationException(new Throwable("Cannot remove items from usuarioAdmCollection"));
            }
        }
        for (UsuarioAdm value : usuarioAdmCollectionNew) {
            if (!usuarioAdmCollection.contains(value)) {
                Usuario oldEntity = value.getUsuario();
                value.setUsuario(entity);
                if (oldEntity != null && !oldEntity.equals(entity)) {
                    oldEntity.getUsuarioAdmCollection().remove(value);
                }
            }
        }
        return entity;
    }

    /**
     * Deletes the entity.
     *
     * @param entity the entity to deletle
     */
    private void deleteEntity(Usuario entity) {
        if (!entity.getUsuarioCliCollection().isEmpty()) {
            throw new WebApplicationException(new Throwable("Cannot delete entity because usuarioCliCollection is not empty."));
        }
        if (!entity.getPedidoCollection().isEmpty()) {
            throw new WebApplicationException(new Throwable("Cannot delete entity because pedidoCollection is not empty."));
        }
        if (!entity.getUsuarioAdmCollection().isEmpty()) {
            throw new WebApplicationException(new Throwable("Cannot delete entity because usuarioAdmCollection is not empty."));
        }
        em.remove(entity);
    }

    /**
     * Returns a dynamic instance of UsuarioClisResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of UsuarioClisResource
     */
    @Path("usuarioCliCollection/")
    public UsuarioClisResource getUsuarioCliCollectionResource() {
        usuarioCliCollectionResourceSub.setParent(getEntity());
        return usuarioCliCollectionResourceSub;
    }

    /**
     * Returns a dynamic instance of PedidoesResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of PedidoesResource
     */
    @Path("pedidoCollection/")
    public PedidoesResource getPedidoCollectionResource() {
        pedidoCollectionResourceSub.setParent(getEntity());
        return pedidoCollectionResourceSub;
    }

    /**
     * Returns a dynamic instance of UsuarioAdmsResource used for entity navigation.
     *
     * @param id identifier for the parent entity
     * @return an instance of UsuarioAdmsResource
     */
    @Path("usuarioAdmCollection/")
    public UsuarioAdmsResource getUsuarioAdmCollectionResource() {
        usuarioAdmCollectionResourceSub.setParent(getEntity());
        return usuarioAdmCollectionResourceSub;
    }

    @Stateless(name = "UsuarioResource.UsuarioCliCollectionResourceSub")
    public static class UsuarioCliCollectionResourceSub extends UsuarioClisResource {

        private Usuario parent;

        public void setParent(Usuario parent) {
            this.parent = parent;
        }

        @Override
        protected Collection<UsuarioCli> getEntities(int start, int max, String query) {
            Collection<UsuarioCli> result = new java.util.ArrayList<UsuarioCli>();
            int index = 0;
            for (UsuarioCli e : parent.getUsuarioCliCollection()) {
                if (index >= start && (index - start) < max) {
                    result.add(e);
                }
                index++;
            }
            return result;
        }
    }

    @Stateless(name = "UsuarioResource.PedidoCollectionResourceSub")
    public static class PedidoCollectionResourceSub extends PedidoesResource {

        private Usuario parent;

        public void setParent(Usuario parent) {
            this.parent = parent;
        }

        @Override
        protected Collection<Pedido> getEntities(int start, int max, String query) {
            Collection<Pedido> result = new java.util.ArrayList<Pedido>();
            int index = 0;
            for (Pedido e : parent.getPedidoCollection()) {
                if (index >= start && (index - start) < max) {
                    result.add(e);
                }
                index++;
            }
            return result;
        }
    }

    @Stateless(name = "UsuarioResource.UsuarioAdmCollectionResourceSub")
    public static class UsuarioAdmCollectionResourceSub extends UsuarioAdmsResource {

        private Usuario parent;

        public void setParent(Usuario parent) {
            this.parent = parent;
        }

        @Override
        protected Collection<UsuarioAdm> getEntities(int start, int max, String query) {
            Collection<UsuarioAdm> result = new java.util.ArrayList<UsuarioAdm>();
            int index = 0;
            for (UsuarioAdm e : parent.getUsuarioAdmCollection()) {
                if (index >= start && (index - start) < max) {
                    result.add(e);
                }
                index++;
            }
            return result;
        }
    }
}
